<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Matrix\Exception;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $appends = ['total_money', 'permissions'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function address()
    {
        return $this->hasMany(Address::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function getTotalMoneyAttribute()
    {
        $id = $this->id;
        $order = Cache::remember('order_total_money_' . $id, 86400, function () use ($id) {
            return Order::where('user_id', $id)->whereNotNull('pay_time')->get()->toArray();
        });
        return array_sum(array_column($order, 'total_money'));
    }

    public function getPermissionsAttribute()
    {
        $is_admin = $this->is_admin;
        if ($is_admin === '0') {
            $permissions = null;
        } else {
            $mall_ids = unserialize($this->is_admin);
            $mall_names = Mall::find($mall_ids)->pluck('name')->toArray();
            if (in_array(0, $mall_ids)) {
                array_unshift($mall_names, '超级管理员');
            }
            $permissions = implode(' | ', $mall_names);
        }

        return $permissions;

    }

    public function userlog()
    {
        return $this->hasMany(UserLog::class);
    }


}
